package ArticleService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/BaseService"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

func Update(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	// 修改时间
	data["update_at"] = time.Now().Unix()
	// 增加附加数据
	if req.UpdateInsertData != nil {
		otherData := req.UpdateInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 删除更新时不需要的字段
	BaseService.DelIgnoreProperty(data, req.UpdateIgnoreProperty)
	// 编辑前方法
	if req.UpdateBeforeFn != nil {
		respRes := req.UpdateBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}

	// 别名不重复
	alias := r.GetString("alias")
	if alias == "" {
		return response.FailByRequestMessage(nil, "别名不能为空")
	}

	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where("alias", alias).
		Where("id != ?", req.Id).Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if count > 0 {
		return response.FailByRequestMessage(nil, "别名重复")
	}

	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where("id", req.Id).Update(data)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err := res.RowsAffected()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if row > 0 {
		// 更新 article_content
		res, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx,
			"article_content",
		).Where(
			"article_id",
			req.Id,
		).Save(g.Map{
			"article_id": req.Id,
			"content":    r.GetString("content"),
		})

		if req.UpdateAfterFn != nil {
			respRes := req.UpdateAfterFn(r, data, g.Map{
				"id": data["id"],
			})
			if respRes.Code != 0 {
				return respRes
			}
		}
		return response.SuccessByRequestMessage(nil, "编辑成功")
	} else {
		return response.FailByRequestMessage(nil, "编辑失败")
	}
}
